package com.example.autopera.辅助类演示;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Code_lemon
 * @version 1.0.0
 * @description TODO 信号灯辅助类实现
 * @date 2024/10/22 20:59
 * @title SemaphoreDemo
 */

// 6啊；辆车，3个停车位
public class SemaphoreDemo {

    public static void main(String[] args) {

        // 创建Semaphore，设置许可数量
        Semaphore semaphore = new Semaphore(3);

        // 模拟6辆车
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                try {
                    // 抢占
                    semaphore.acquire();

                    // 使用
                    System.out.println(Thread.currentThread().getName() + "号车抢占了车位");
                    // 设置随机停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));

                    System.out.println(Thread.currentThread().getName() + "号车------离开了车位");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }

    }

}
